package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.contants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMaterialMapper newsMaterialMapper;

    @Autowired
    private WmMaterialMapper materialMapper;

    @Autowired
    private WmNewsAutoScanService newsAutoScanService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 1.检查参数
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();
        // 2.构建分页参数
        IPage page = new Page(dto.getPage(), dto.getSize());
        // 3.创建查询条件
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        // 判断是否有关键字模糊查询
        if (StringUtils.isNotEmpty(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        // 判断是否查询时间范围
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        // 判断查询频道
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        // 判断查询状态
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        // 根据当前用户id查询
        wrapper.eq(WmNews::getUserId, user.getId());
        // 按照发布时间倒序排列
        wrapper.orderByDesc(WmNews::getCreatedTime);
        // 4.分页查询
        page(page, wrapper);

        // 返回结果
        PageResponseResult responseResult =
                new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 发布、修改文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    @GlobalTransactional
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        // 1.检查参数
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.保存或者修改文章
        WmNews wmNews = saveOrUpdateNews(dto);

        // 3.判断当前是发布文章还是保存草稿,status为0则保存草稿
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //获取文章内容图片信息
        List<String> materials = ectractUrlInfo(dto.getContent());

        // 4.保存文章内容图片和素材的关系
        saveRelativeInfoForContent(materials, wmNews.getId());

        // 5.保存封面图片和素材的关系
        saveRelativeInfoForCover(dto, wmNews, materials);

        // 审核文章
        // newsAutoScanService.autoScanWmNews(wmNews.getId());
        wmNewsTaskService.addWmNewsToTask(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    @Async
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章id不可缺少");
        }

        // 根据id查询文章
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery()
                .eq(WmNews::getId, dto.getId()));
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        // 判断当前文章是否已经发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,
                    "当前文章不是发布状态,不能上下架");
        }

        // 更新文章上下架状态
        wmNews.setEnable(dto.getEnable());
        updateById(wmNews);

        // 异步请求修改文章配置
        Map<String, Object> map = new HashMap<>();
        map.put("id",wmNews.getArticleId());
        if (wmNews.getEnable().equals((short) 0)){
            map.put("enable",true);
        }else {
            map.put("enable",false);
        }

        kafkaTemplate.send("wmNews-topic",JSON.toJSONString(map));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面图片和素材的关系到数据库
     *
     * @param dto
     * @param wmNews    如果文章封面选择自动，则自动匹配封面
     *                  * 匹配规则：
     *                  *     如果内容图片大于等于3  则是多图，截图3张图片作为封面
     *                  *     如果内容图片大于等于1&&小于3  则是单图，截图1张图片作为封面
     * @param materials
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        // 获取封面图片信息
        List<String> images = dto.getImages();
        // 自动匹配封面
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            int size = images.size();
            if (size >= 3) {
                // 多图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else if (size >= 1 && size < 3) {
                // 单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else {
                // 无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            // 更新文章封面
            updateById(wmNews);
        }
        saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);

    }

    /**
     * 保存文章内容图片和素材的关系到数据库
     *
     * @param materials
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        // 判断内容中是否有图片,如果有才需要保存内容关系
        if (materials != null && materials.size() > 0) {
            // 图片可能有重复,去重
            materials = materials.stream().distinct().collect(Collectors.toList());
            // 获取当前登录用户
            WmUser user = WmThreadLocalUtil.getUser();
            if (user == null) {
                throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
            }
            // 根据图片url查询对应的id
            List<WmMaterial> materialList = materialMapper.selectList(Wrappers.
                    <WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials)
                    .eq(WmMaterial::getUserId, user.getId()));

            if (materialList == null || materialList.size() == 0) {
                // 素材没找到,抛出异常告知用户素材引用失效
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            // 获取id
            List<Integer> materialIds = new ArrayList<>();
            for (WmMaterial material : materialList) {
                materialIds.add(material.getId());
            }
            // 保存文章和素材关系
            newsMaterialMapper.saveRelations(materialIds, newsId, type);
        }
    }

    /**
     * 获取文章内容中的图片信息
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> materials = new ArrayList<>();
        List<Map> mapList = JSON.parseArray(content, Map.class);
        for (Map map : mapList) {
            if (map.get("type").equals("image")) {
                materials.add(map.get("value").toString());
            }
        }
        return materials;
    }

    /**
     * 保存或者修改文章
     *
     * @param dto
     * @return
     */
    private WmNews saveOrUpdateNews(WmNewsDto dto) {
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);

        // 处理封面图片信息
        String images = StringUtils.join(dto.getImages(), ",");
        wmNews.setImages(images);

        // 填充其他数据
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());

        // 如果当前的文章布局为自动,存储-1到数据库会报错,先设置为null
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }

        // 判断当前为提交还是修改文章
        if (dto.getId() == null) {
            // 当前请求为新增文章
            save(wmNews);
        } else {
            // 当前请求为修改文章,需要先删除素材和文章的关系
            newsMaterialMapper.delete(Wrappers.
                    <WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, dto.getId()));
            updateById(wmNews);
        }

        return wmNews;
    }
}
